﻿using System;
using UnityEngine;

namespace ProjectDanmaku.Core
{
    [ExecuteAlways]
    public class CameraAspectController : MonoBehaviour
    {
        public Vector2 aspect = new Vector2(16, 9);

        private float _lastAspect = -1f;
        private Camera _camera;

        private void UpdateCameraAspect()
        {
            var calcAspect = aspect.x / aspect.y;
            var screenAspect = (float)Screen.width / Screen.height;
            if (Mathf.Approximately(_lastAspect, screenAspect))
            {
                return;
            }
            
            _lastAspect = screenAspect;
            
            if (aspect.y != 0f && screenAspect <= calcAspect)
            {
                _camera.aspect = calcAspect;
                var rectH = Screen.width / calcAspect / Screen.height;
                _camera.rect = new Rect(0, (1 - rectH) / 2f, 1, rectH);
            }
            else if (aspect.y != 0f && screenAspect > calcAspect)
            {
                _camera.aspect = calcAspect;
                var rectW = calcAspect * Screen.height / Screen.width;
                _camera.rect = new Rect(0.5f - rectW / 2f, 0, rectW, 1);
            }
        }
        
        private void Awake()
        {
            _camera = GetComponent<Camera>();
        }

        private void Start()
        {
            if (Application.isMobilePlatform)
                Application.targetFrameRate = 144;
            
            UpdateCameraAspect();
        }

        private void Update()
        {
            UpdateCameraAspect();
        }
    }
}